﻿using System;
using System.Linq.Expressions;

namespace Vasuleg.UIDrive
{
    public class UIDriveCommonNode<T> : UIDriveNode<T>
    {
        private readonly Expression<Func<T>> _eval;
        private Func<T> _compileEval;

        public UIDriveCommonNode(UIDrive uiDrive, Action<T> targetAssignFunc, Expression<Func<T>> eval) : base(uiDrive, targetAssignFunc)
        {
            _eval = eval;
        }

        internal override void Awake()
        {
            var memberPathNodes = ExpressionUtils.SelectMemberPath(_eval);
            AddRangeMemberPathNode(memberPathNodes);
            _compileEval = _eval.Compile();
        }

        protected override void OnDriveNoticeDataChange(NoticeDataContext context)
        {
            T resValue;
            try
            {
                resValue = _compileEval();
            }
            catch
            {
                resValue = DefaultValue;
            }
            TargetAssign(resValue);
        }
    }
}